<template>
  <div class="border-1 border-solid border-#e4e4e4 p-2">
    <div class="block-title">
      自定义文件 <el-button type="primary" style="margin-left: 20px" :disabled="disabled" @click="handleSelect">自定义文件</el-button>
    </div>
    <div class="mt-2 font-size-3 color-#8d8d8d">
      {{ allFiles }}
    </div>
    <el-dialog v-if="dialogVisible" v-model="dialogVisible" title="自定义文件" width="1000px" :before-close="handleClose">
      <div class="border-1 border-solid border-#e4e4e4 p-2">
        <!-- <el-scrollbar style="height: 300px"> -->
        <!-- <div v-for="(item, index) in fileList" :key="'file-item' + index" class="flex flex-justify-between flex-items-center">
            <div class="w-200 color-#8d8d8d">
              {{ item.name }}<span v-if="item.files.length" class="color-#409EFF">（已上传{{ item.files.length }}个文件）</span>
            </div>
            <div v-if="!loading" class="pr-3">
              <el-button type="primary" link size="small" @click="handleRemove(index)">删除</el-button>
              <el-button type="primary" link size="small" @click="handleUpload(index)">上传文件</el-button>
            </div>
          </div> -->
        <el-table :data="fileList" height="300px">
          <el-table-column prop="name" label="文件名" min-width="200" />
          <el-table-column prop="files" label="文件数" width="100">
            <template #default="scope">
              {{ scope.row.files.length }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button type="primary" link size="small" @click="handleRemove(scope.$index)">删除</el-button>
              <el-button type="primary" link size="small" @click="handleUpload(scope.$index)">上传文件</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- </el-scrollbar> -->
      </div>
      <div class="mt-2">
        <el-button type="primary" @click="handleCreateFolder">创建文件夹</el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-loading="loading" type="primary" @click="handleSubmit">提交</el-button>
          <el-button v-loading="loading" @click="handleClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-if="dialogFolderVisible"
      v-model="dialogFolderVisible"
      append-to-body
      title="创建文件夹"
      width="500px"
      :before-close="handleFolderClose"
    >
      <div class="text-center">
        <el-input v-model="folderName" placeholder="请输入文件夹" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleFolderSubmit">提交</el-button>
          <el-button @click="handleFolderClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-if="dialogUploadVisible"
      v-model="dialogUploadVisible"
      append-to-body
      title="上传文件"
      width="500px"
      :before-close="handleUploadClose"
    >
      <div class="flex flex-justify-between">
        <el-upload v-model:file-list="files" class="mt-2" :auto-upload="false" action="#" multiple :limit="limit" :on-exceed="handleExceed">
          <el-button type="primary" :disabled="uploadLoading">选择上传文件</el-button>
        </el-upload>
        <div class="mt-4">已选择{{ files.length }}份文件</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-loading="uploadLoading" type="primary" @click="handleUploadSubmit">提交</el-button>
          <el-button v-loading="uploadLoading" @click="handleUploadClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CustomFile" lang="ts">
import { uploadLoadExperiment, uploadCustomization } from '@/api/loadProcessingAlgorithm/loadTaskManagement/index';
import type { UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const prop = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  loadExperimentId: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['update:modelValue', 'update-file']);
const dialogVisible = ref(false);
const dialogUploadVisible = ref(false);
const dialogFolderVisible = ref(false);
const fileList = ref([]);
const files = ref([]);
const allFiles = ref('');
const loading = ref(false);
const uploadLoading = ref(false);
const folderName = ref('');
const currentItemIndex = ref(0);
const handleCreateFolder = () => {
  folderName.value = '';
  dialogFolderVisible.value = true;
};
const handleFolderClose = () => {
  dialogFolderVisible.value = false;
};
const handleFolderSubmit = () => {
  if (!folderName.value) {
    proxy?.$modal.msgWarning('请输入文件夹！');
    return false;
  }
  fileList.value.push({ name: folderName.value, files: [] });
  dialogFolderVisible.value = false;
};
const handleSelect = () => {
  fileList.value = [];
  dialogVisible.value = true;
};
const handleUploadClose = () => {
  dialogUploadVisible.value = false;
};
const handleClose = () => {
  dialogVisible.value = false;
};
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`当前限制${prop.limit}, 你选择了这次选择了 ${files.length} 个文件, 共选择了${files.length + uploadFiles.length}文件`);
};
const handleRemove = async (index) => {
  await proxy?.$modal.confirm('是否确认删除该文件夹及文件?');
  fileList.value.splice(index, 1);
};
const handleSubmit = async () => {
  loading.value = true;
  for (let i = 0; i < fileList.value.length; i++) {
    const item = fileList.value[i];
    if (!item.files.length) {
      loading.value = false;
      proxy?.$modal.msgWarning('请在没上传的文件夹中上传文件！');
      return false;
    }
  }
  const formData = new FormData();
  formData.append('parameterName', 'uploadCustomizationFile');
  formData.append('loadExperimentId', prop.loadExperimentId);
  const result = [];
  fileList.value.forEach((item) => {
    item.files.forEach((el) => {
      console.log(el);
      const name = '/' + item.name + '/' + el.name;
      result.push(name);
      formData.append('files', el.raw, name);
    });
  });
  const res = await uploadCustomization(formData).catch(() => {
    loading.value = false;
  });
  if (res.code === 200) {
    allFiles.value = result.join(',');
    emit('update:modelValue', allFiles.value);
    emit('update-file');
    loading.value = false;
    dialogVisible.value = false;
  }
};
const handleUpload = (index) => {
  files.value = [];
  currentItemIndex.value = index;
  dialogUploadVisible.value = true;
};
const handleUploadSubmit = () => {
  uploadLoading.value = true;
  if (!files.value.length) {
    proxy?.$modal.msgWarning('请上传文件！');
    uploadLoading.value = false;
    return false;
  }
  const obj = fileList.value[currentItemIndex.value];
  obj.files = files.value;
  uploadLoading.value = false;
  dialogUploadVisible.value = false;
};
watch(
  () => prop.modelValue,
  () => {
    if (prop.modelValue) {
      allFiles.value = prop.modelValue;
    }
  }
);
onMounted(() => {
  if (prop.modelValue) {
    allFiles.value = prop.modelValue;
  }
});
</script>

<style lang="scss" scoped>
.upload-left {
  border-right: 1px solid #e4e4e4;
  width: 150px;
  position: relative;
  cursor: pointer;
}
.upload-icon {
  position: absolute;
  top: 50%;
  text-align: center;
  transform: translate(10px, -50%);
}
.upload-text {
  font-size: 10px;
  color: #8d8d8d;
}
.dialog-footer {
  text-align: center;
}
</style>
